#!/usr/bin/python env
#-*- coding:utf-8 -*-
'''
#=============================================================================
#     FileName: blog.py
#         Desc: Show the blog
#       Author: cold night
#        Email: wh_linux@126.com
#     HomePage: http://www.linuxzen.com/
#      Version: 0.0.1
#   LastChange: 2012-05-16 15:13:33
#      History:
#=============================================================================
'''

from setting import TEMPLATE, page_size
from bottle import route,template, response, request, redirect
from re import match
from model import model
from model.common import get_subdate

# 定义文章显示通用
def setTempVar():
    TEMPLATE['allcates'] = model.get_categories()
    TEMPLATE['dates'] = model.get_artdate()
    TEMPLATE['toptenart'] , c= model.get_articles()
    TEMPLATE['currurl'] = request.url
    TEMPLATE['BLOG_NAME'] = model.get_option('BLOG_NAME')
    TEMPLATE['SUBTITLE'] = model.get_option('SUBTITLE')
    TEMPLATE['ADMINMAIL'] = model.get_option('ADMINMAIL')
    TEMPLATE['user'] = request.COOKIES.get('user', '')
    return TEMPLATE
    
#==========================================================================
# 首页显示
#==========================================================================
@route('/')
@route('/page/:page')
def index(page=1):
    '''
    用于显示首页,显示文章列表
    '''
    TEMPLATE['posts'],TEMPLATE['count'] = model.get_articles(index = int(page), size=page_size)
    
    TEMPLATE['title'] = TEMPLATE['BLOG_NAME'] + ' | ' + TEMPLATE['SUBTITLE']
    # 合并通用模板变量
    TEMPLATE.update(setTempVar())
    
    return template('index.html', TEMPLATE)



# 按分类显示文章
@route('/categories/:cate/')
@route('/categories/:cate/page/:page')
def showofcate(cate, page=1):
    '''
    按分类显示文章
    cate -> 获取字url,分类名称,
    '''
    TEMPLATE['title'] = cate + ' | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['posts'], TEMPLATE['count'] = model.get_articles(index=int(page), size=page_size, categories = cate)
    TEMPLATE.update(setTempVar())

    return template('index.html', TEMPLATE)


# 按标签显示文章
@route('/tags/:tag/')
@route('/tags/:tag/page/:page')
def showoftag(tag, page=1):
    '''
    按标签分类显示文章
    '''
    TEMPLATE['posts'], TEMPLATE['count'] = model.get_articles(index=int(page), size=page_size, tags=tag)
    TEMPLATE['title'] = tag + ' | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE.update(setTempVar())

    return template('index.html', TEMPLATE)




# 按日期显示分页
@route('/archrives/date/:year#\d+#/:month#\d+#/')
@route('/archrives/date/:year/:month/page/:page#\d+#/')
def showofdate_page(year, month=1, page=1):
    ''' 按日期归档显示文章分页'''
    start, end = get_subdate(year, month)
    query = {"date":{"$gte":start, "$lt":end}}
    TEMPLATE['posts'], TEMPLATE['count'] = model.get_articles(index=int(page),size=page_size, **query)
    TEMPLATE['title'] = year + '年' + month + '月 | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE.update(setTempVar())
    return template('index.html', TEMPLATE)



# 单页显示文章
@route('/archrives/:aid#(?:[0-9a-f]{24}|\d+)#')
@route('/archrives/:aid#(?:[0-9a-f]{24}|\d+)#/page/:page')
def article_show(aid, page=1):
    '''
    单页显示文章
    '''
    
    # 获取客户端ip
    remoteip = request.environ.get('REMOTE_ADDR')

    artcookie = remoteip+'ip'+aid
    
    # 判断cookie是否存在
    if artcookie in request.COOKIES.keys():
        # 存在则更新有效时间
        response.COOKIES[artcookie] = True
        response.COOKIES[artcookie]['max-age'] = 500
        addviews = False
    else:
        addviews =True
        # 并设置cookie
        response.COOKIES[artcookie] = True
        response.COOKIES[artcookie]['max-age'] = 500


    #为前台传递评论数据
    TEMPLATE['comments'], TEMPLATE['count'] = model.get_comments(aid, index=page, size=page_size)
    TEMPLATE['posts'] = model.get_articles(artid=aid, addviews = addviews)
    TEMPLATE.update(setTempVar())

    return template('article.html', TEMPLATE)




@route('/comments/post',method="POST")
def comments_post():
    '''
    处理文章提交的评论
    提交评论POST表单包括:
    name -> 姓名
    email -> 邮箱
    website -> 个人主页
    content -> 评论内容
    '''
    # 获取表单数据
    comments = request.POST
    name, email, website, content, artid = comments['name'], comments['email'], comments['website'],comments['content'], comments['artid']
    # 获取id
    comments_dict = {
            "name":name,
            "email":email,
            "website":website,
            "content":content,
            }
    model.comment_add(artid, comments_dict)
        
    redirect('/archrives/'+str(artid) + '#comments')
